package com.zlq.add.Thread;

import java.util.concurrent.Semaphore;

/**
 * Semaphore同步器
 * 特征：
 * 1.经典的信号量，通过计数器控制对共享资源的访问
 * 2.Semaphore(int count):创建拥有count个许可证的信号量
 * 3.acquire()/acquire(int num):获取1/num个许可证
 * 4.release/release(int num):获取1/num个许可证
 */

public class SemaphoreThread {
    public static void main(String[] args) {
        //初始化两个银行服务柜台(窗口)
        Semaphore semaphore = new Semaphore(2);

        //有A,B,C三个客户
        Person a = new Person(semaphore, "A");
        a.start();

        Person b = new Person(semaphore, "B");
        b.start();

        Person c = new Person(semaphore, "C");
        c.start();


    }

}

class Person extends Thread {
    private Semaphore semaphore;

    public Person(Semaphore semaphore, String name) {
        setName(name);
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        System.out.println(getName() + "在等待...");
        try {
            //获取许可证
            semaphore.acquire();
            System.out.println(getName() + "在服务...");
            // 睡眠一秒
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(getName() + "已完成!..");
        //释放信号量
        semaphore.release();
    }
}
